package com.ler.yrmall.search.service.impl;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.ler.yrmall.search.config.ElasticsearchConf;
import com.ler.yrmall.search.constant.Constant;
import com.ler.yrmall.search.dto.SkuEsModelDTO;
import com.ler.yrmall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @author leron
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productSale(List<SkuEsModelDTO> skuList) {
        Assert.notEmpty(skuList,() -> new RuntimeException("商品列表不能为空"));
        BulkRequest bulkRequest = new BulkRequest();
        skuList.forEach(item -> {
            IndexRequest indexRequest = new IndexRequest(Constant.PRODUCT_INDEX);
            indexRequest.id(item.getId().toString());
            indexRequest.source(JSON.toJSONString(item), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        //BulkRequest bulkRequest, RequestOptions options
        BulkResponse bulk;
        try {
            bulk = restHighLevelClient.bulk(bulkRequest, ElasticsearchConf.COMMON_OPTIONS);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return bulk.hasFailures();
    }

    @Override
    public Boolean productSoldOut(List<Long> skuIds) {
        Assert.notEmpty(skuIds,() -> new RuntimeException("商品列表不能为空"));
        BulkRequest bulkRequest = new BulkRequest();
        skuIds.forEach(sku -> bulkRequest.add(new DeleteRequest(Constant.PRODUCT_INDEX, sku.toString())));
        BulkResponse response;
        try {
            response = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return response.hasFailures();
    }
}
